<template>
	<div class="pagination-container" :style="{
	       'background': config.config.property.bgColor,
	       'width': config.config.property.width + 'px',
	       'height': config.config.property.height + 'px',
	     }">
		<div id="main" ref="chartContainer" style="width: 100%; height: 100%; z-index: 10"></div>
		<img class="img" src="./images/icon_1.png" v-if="config.config.property.type == 1" />
		<img class="img" src="./images/icon_2.png" v-if="config.config.property.type == 2" />
		<img class="img" src="./images/icon_3.png" v-if="config.config.property.type == 3" />
	</div>

</template>
<script>
	import * as echarts from 'echarts'
	import chartBase from '@/mixin/chart-base.js';
	import emitComponentBase from '@/mixin/emit-component-base.js';
	import dataModel from '@/models/panel-config-data.js';
	import {
		checkNegative
	} from '@/utils/util';
	import {
		mapState
	} from 'vuex';
	import config from './config/config';



	export default {
		name: 'AnnularChart',
		components: {

		},
		mixins: [chartBase, emitComponentBase],
		props: ['pareentId', 'widgetId', 'widgetInstanceId', 'widgetName', 'identifier', 'layout', 'w', 'h', 'Item'],
		data() {
			return {
				chart: null, // 用于存储 ECharts 实例的引用
				echartsOptionData: [{
					'val': 64,
				}, ],
			};
		},
		computed: {
			...mapState({}),
		},
		watch: {

		},
		created() {
			this.orgConfig = config;
			this.config = JSON.parse(JSON.stringify(this.orgConfig));
			this.chartId = `${this.widgetInstanceId}_01`;

		},
		mounted() {
			if (window.isLocalEnv) {
				this.loadWidget();
			}
		},
		methods: {

			// 初始加载时 以及 编排面更改配置时 触发
			loadWidget(pageStatus) {
				this.pageStatus = pageStatus;
				this.updateConfigProperty();
				this.updateConfigData();
				if (window.isLocalEnv || this.emitComponentStatus) {
					this.updateParams(pageStatus);
					if (!this.isRealTime) {
						this.debounceGetData();
					}
				}
				this.afterLoadWidget();
				this.checkNegative(this.apiResult);
			},

			// 接收xvue发来的实时数据
			handleRealTimeCommunication(realTimeData) {
				if (this.config.config.property.isDebounce && this.isStopRealData) {
					return;
				}

				const result = this.getResult(realTimeData);
				if (this.isNoData || this.autoRefreshIsSameRes(result)) {
					this.isLoading = false;
					return;
				}
				const {
					data,
					property
				} = this.config.config;

				// api请求，拿到数据
				if (data.dataSourceType !== 'xMinerRedisRealTime') {
					this.getCorrectParams(this.params, data.dataSourceType); // 参数存入xvue，导出数据时使用
				}
				// this.apiResult = result;
				// this.lastParams = null;
				// this.sendDataToConfig(result);
				// const convertedData = convertData(result, property);
				// if (convertedData === -1) {
				//   this.$message.error(this.$demoi18n('view.dataSourceTypeErr'));
				//   this.setDataException();
				//   return;
				// }
				// this.generateChart(convertedData);
				// this.isLoading = false;
			},
			acceptEvtMsg(paramters, key, obj) {
				this.checkUpdateParams(obj);
			},
			checkUpdateParams(obj) {
				// 检查下是否和本组件有关
				const _obj = obj || {};
				let oo = {}
				let flag = false;
				for (const key in _obj) {
					if (key.indexOf(EMIT_PARAMS_OBJ) > -1) {
						const o = _obj[key];
						if (o.eventKey) {
							const event = this.config.events.find(e => e.type === 'in' && e.key === o.eventKey);
							if (event) {
								flag = true;
								oo = o
							}
							break;
						}
					}
				}
				if (flag) {
					// 和本组件有关再执行组件接收到事件后的相关操作
					console.log('_obj', _obj)
					console.log('oo', oo)

					this.isNoData = false;
					this.isLoading = true;
					this.autoRefresh();
					const alarm_id = oo?.parameters[oo?.keys[0]]
					let param = {
						code: 'alarm_id',
						value: alarm_id
					}
					let paramOo = [param]

					// api请求，拿到数据
					const {
						data
					} = this.config.config
					this.isLoading = true
					const method = `getChartData${data.dataSourceType}`;
					const trueParams = this.getCorrectParams(this.params, data.dataSourceType);
					trueParams = {
						...trueParams,
						params: paramOo,
					};

					dataModel[method](trueParams, data)
						.then(result => {

							this.echartsOptionData = result
							this.echartsOptionfunction(result)

						})
						.catch(err => {
							this.handleChartDataError(err);
						})
						.finally(() => {
							this.isLoading = false;
						});
				}
			},
			getChartData() {
				const {
					data,
					property
				} = this.config.config;

				// 如果dataSourceType为静态数据,把数据放到Vuex，发出事件，然后退出
				if (data.dataSourceType === 'staticData') {

					this.echartsOptionfunction(this.echartsOptionData)

					// 重置数据异常状态
					this.resetAbnormalType();
					return;
				}

				// api请求，拿到数据
				if (data.dataSourceType) {
					this.isNoData = false;
					this.isLoading = true;
					this.autoRefresh();
					const method = `getChartData${data.dataSourceType}`;
					const params = this.getCorrectParams(this.params, data.dataSourceType);
					dataModel[method](params, data)
						.then(result => {
							this.echartsOptionData = result
							this.echartsOptionfunction(this.echartsOptionData)


							// 重置数据异常状态
							this.resetAbnormalType();
							this.reportIfFieldsError(this.getParams()?.propertyMapping, result);
							if (this.autoRefreshIsSameRes(result)) {
								return;
							}

						})
						.catch(err => {
							this.handleChartDataError(err);
						})
						.finally(() => {
							this.isLoading = false;
						});
				} else {
					// 如果在用户面，则给提示
					if (this.$route.name === 'userHomePage') {
						this.$message({
							message: this.$demoi18n('view.dataSourceTypeEmpty'),
							type: 'warning',
						});
					}
				}
			},
			echartsOptionfunction(echartsData) {
				console.log('图表内', echartsData)
				let chart = {}
				if (echartsData.length > 0) {
					chart = echartsData[0]
				}
				const data1 = chart.val
				const data2 = 100 - data1
				const option = {
					grid: {
						top: `0%`,
						left: `0%`, // 距离容器左侧的距离
						right: `0%`, // 距离容器右侧的距离
						bottom: `0%`, // 距离容器底部的距离
						containLabel: true, // grid区域是否包含坐标轴的标签
					},
					tooltip: {
						trigger: 'item',
						show: false,
					},
					legend: {
						show: false, // 关闭图例显示
					},
					series: [{
						name: 'Access From',
						type: 'pie',
						radius: ['85%', '90%'],
						startAngle: 0, // 设置起始角度为 90°
						avoidLabelOverlap: false,
						label: {
							show: false,
							position: 'center',
						},
						emphasis: {
							itemStyle: {
								// 设置 hover 状态的样式（保持不变）
								shadowBlur: 0,
								shadowOffsetX: 0,
								shadowColor: 'rgba(0, 0, 0, 0)',
							},
						},
						labelLine: {
							show: false,
						},
						data: [{
								value: data1,
								name: 'Search Engine',
								itemStyle: {
									color: `${this.config.config.property.xlincolor}`
								}
							},
							{
								value: data2,
								name: 'Direct',
								itemStyle: {
									color: 'rgba(0, 0, 0, 0)'
								}
							},
						],
					}, ],
					// 中间显示百分比
					graphic: {
						elements: [{
							type: 'text',
							left: 'center',
							top: '60%',
							style: {
								text: `${data1}%`, // 手动设置中心百分比，后面可以根据数据动态更新
								font: 'bold 24px sans-serif',
								fill: '#fff',
							},
						}, ],
					},
				}
				console.log(this.config.config.property, option, 'property');

				this.chart = echarts.init(this.$refs.chartContainer)
				this.chart.setOption(option)
			},
			// itemClick(params) {
			// 	console.log(this.widgetInstanceId)
			//   const orgEvtKey = this.orgConfig.events[0].key
			//   const outEvt = this.config.events[0]
			//   const { key } = outEvt.parameters[0] // key: 对应xminer接口中的参数/编码
			//   const { paramKey } = outEvt // paramKey: 对应数据面板中的字段名，如s，y
			//   console.log('=======params============', params)
			//   const outObj = {
			//     emit_params_obj: {
			//       eventKey: outEvt.key,
			//       type: 'terms',
			//       keys: [key],
			//       parameters: {
			//         [key]: params[paramKey],
			//       },
			//       widgetInstanceId: this.widgetInstanceId,
			//       sendTime: new Date().getTime(),
			//     },
			//   }
			//   // console.log("===================",outObj)
			//   // xvue提供的emit方法，用于发出事件的
			//   if (import.meta.env.PROD) {
			//     adapterComponent.emit(orgEvtKey, outObj)
			//   } else {
			//     emit(orgEvtKey, outObj)
			//   }
			// },
			// getTooltip() {
			//   return {
			//     config: this.config.config.property.tooltip || {},
			//     vars: {},
			//     params: this.params,
			//     parentComp: this,
			//   };
			// },
			checkNegative,
			// itemClick(params, data) {
			// 	console.log(params)
			//   this.chartClick(params, data);
			//   if (params) {
			//     this.sendAdvancedLinkagge({...params});
			//   }
			// },
			// handleAsTooltip(filterRes) {
			//   const { property } = this.config.config;
			//   const convertedData = convertData(filterRes, property);
			//   this.generateChart(convertedData);
			// },
		},
	};
</script>
<style lang="less" scoped>
	// 图表通用样式，主要有黑色loading 和 黑色 ‘没有数据’，样式名需一致
	@import '../../common/chart.less';
	.pagination-container {
	  position: relative;
	}
	.img {
	  position: absolute;
	  left: 0px;
	  top: 0px;
	}
</style>
<style>
	/* 全局loading样式修改 */

	.chartMain .loading .el-loading-spinner .circular {
		width: 34px !important;
		height: 34px !important;
	}

	.chartMain .el-dialog__header {
		padding: 9px 20px 10px !important;
		background: #2a3352 !important;
		text-align: left;
		box-sizing: border-box;
		height: 50px;
		line-height: 32px;
	}

	.chartMain .el-dialog__title {
		text-align: left;
		/* font-size: 18px; */
		line-height: 18px !important;
		color: #b2d3fe !important;
	}

	.chartMain .el-dialog__body {
		padding: 10px 20px 30px 20px;
		background: #1a2032 !important;
		line-height: 24px;
		font-size: 14px;
	}

	.chartMain .el-dialog__headerbtn .el-dialog__close {
		color: #b2d3fe !important;
	}

	.chartMain .dialog-footer {
		text-align: right;
		margin-bottom: -14px;
		margin-right: 4px;
	}

	.chartMain .el-dialog__headerbtn {
		top: 15px;
		/* font-size: 18px; */
	}
</style>